package com.zg.utils;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.mqtt.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 从服务端发送消息到客户端
 */
@Slf4j
@Component
public class ServerPublishClient {

    public MqttPublishMessage pushMsgToClient(String topic,Object replay,int packetId ,boolean isDup,MqttQoS qoS,boolean retain){
        String s = JSON.toJSONString(replay);
        ByteBuf byteBuf = Unpooled.wrappedBuffer(s.getBytes());
        MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,isDup, qoS,retain,s.length());
        MqttPublishVariableHeader mqttPublishVariableHeader = new MqttPublishVariableHeader(topic, packetId);
        MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader,mqttPublishVariableHeader, byteBuf);
        return mqttPublishMessage;
    }

}
